/*
 * Copyright 2011 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.android.calllog;

import java.util.Vector;

import nl.biz_e.android.calllog.CallLogItemView.Event;
import nl.biz_e.android.calllog.R.id;
import nl.biz_e.android.calllog.dao.BussinessLogic;
import nl.biz_e.android.calllog.dao.LogDao;
import nl.biz_e.android.calllog.model.CallLogItem;
import nl.biz_e.android.calllog.util.AsyncTaskRunner;
import nl.biz_e.android.calllog.util.AsyncTaskRunner.AsyncCallbackTaskExecutor;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * The CallLoggerActivity Shows a list of Call Log items, and
 * offers a way to choose what items will be logged in the calendar.
 * <p>
 * The configuration of the service can also be reached from here.
 * 
 * @author Joost A. Bloemsma
 */
public class CallloggerActivity extends Activity implements OnClickListener, CallLogItemView.OnCallLogItemClickListener, AsyncCallbackTaskExecutor {
	private static final String DEBUG_TAG = CallloggerActivity.class.getSimpleName();
	private Button btnStart;
	private Button btnTest;
	private LinearLayout llScroll;
	private ScrollViewEx sv;
	private AsyncTaskRunner testRunner;
	
    /** 
     * {@inheritDoc} 
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initControls();
    }
    
    /**
     * Initialise all controls
     */
    private void initControls() {
    	btnStart = (Button)findViewById(id.btnStart);
    	btnTest = (Button)findViewById(id.btnTest);
    	llScroll = (LinearLayout)findViewById(id.llScroll);
    	sv = (ScrollViewEx)findViewById(id.svScroll);
    	btnStart.setOnClickListener(this);
    	btnTest.setOnClickListener(this);
    	registerForContextMenu(sv);
    }
    
    
    /**
     * Triggered when the start button is clicked.
     */
    private void onStartClick() {
    	llScroll.removeAllViews();
    	Vector<CallLogItem> items = LogDao.getInstance().getLogItems();
    	for (CallLogItem itm : items) {
    		addItem(itm);
    	}
    	
    	sv.scrollToEnd();
    }
    
    private void onTestClick() {
    	/*
    	Map<Long,String> cals = _dao.getCalendars();
    	for (String cal : cals.values()) {
    		System.out.println(cal);
    	}
    	*/
    	//startActivityForResult(new Intent(Intent.ACTION_PICK,ContactsContract.CommonDataKinds.Phone.CONTENT_URI),0);
    	
    	Vector<CallLogItem> items = LogDao.getInstance().getLogItems(true);
    	int count = 0;
    	for (CallLogItem item : items) {
    		try {
				BussinessLogic.logItemInCalendar(item);
			} catch (CallLogException e) {
				Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
				Log.e(DEBUG_TAG, e.getMessage(), e);
			}
    	}
    	Toast.makeText(this, "Stored " + String.valueOf(count) + " items", Toast.LENGTH_SHORT).show();
    }
    
    /**
	 * {@inheritDoc}
	 */
	public int executeAsync(AsyncTaskRunner runner) {
		Vector<CallLogItem> items = LogDao.getInstance().getLogItems(true);
    	int count = 0;
    	for (CallLogItem item : items) {
    		try {
				BussinessLogic.logItemInCalendar(item);
				count ++;
			} catch (CallLogException e) {
				//Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
				Log.e(DEBUG_TAG, e.getMessage(), e);
			}
    	}
    	return count;
	}

	
	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println(data);
	}
    
    void addItem(CallLogItem item) {
    	CallLogItemView clView = new CallLogItemView(this,item);
    	llScroll.addView(clView);
    	clView.addOnCallLogItemClickListener(this);
    	if (Log.isLoggable(DEBUG_TAG, Log.DEBUG)) Log.d(DEBUG_TAG, "Added item " + item.getItemId() + " to view");
    }

	/**
	 * {@inheritDoc}
	 */
    public void onClick(View v) {
		if (v == btnStart) {
			onStartClick();
			return;
		}
		if (v == btnTest) {
			onTestClick();
			return;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu , menu);
		Intent prefsIntent = new Intent(getApplicationContext(),CallLogPreferences.class);
		MenuItem prefs = menu.findItem(R.id.settings_option);
		prefs.setIntent(prefsIntent);
		if (Log.isLoggable(DEBUG_TAG, Log.DEBUG)) Log.d(DEBUG_TAG, "Options menu created");
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.settings_option:
			if (Log.isLoggable(DEBUG_TAG, Log.DEBUG)) Log.d(DEBUG_TAG, "Option 'settings' selected");
			startActivity(item.getIntent());
		}
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	public void onCallLogItemClicked(CallLogItemView view, Event event) {
		CallLogItem item = view.getItem();
		if (event == Event.EVENT_STORECAL) {
			try {
				BussinessLogic.logItemInCalendar(item);
				Toast.makeText(this, getString(R.string.msg_item_stored), Toast.LENGTH_SHORT).show();
			} catch (CallLogException e) {
				Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
				Log.e(DEBUG_TAG, e.getMessage(), e);
			}
		}
	
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onContextItemSelected(item);
	}

	
	
}